<?php
namespace Src\middleware;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;


// 自定义 JSON 解析错误处理中间件
class JsonParsingErrorMiddleware implements MiddlewareInterface
{
    public function process(Request $request, RequestHandler $handler): Response
    {
        // 只处理 JSON 类型的请求
        $contentType = $request->getHeaderLine('Content-Type');
        if (strpos($contentType, 'application/json') !== false) {
            $rawBody = (string) $request->getBody();
            // 重置请求体指针（避免后续读取时为空）
            $request->getBody()->rewind();

            // 检查 JSON 有效性
            json_decode($rawBody);
            if (json_last_error() !== JSON_ERROR_NONE) {
                $response = new \Slim\Psr7\Response();
                $response->getBody()->write(json_encode([
                    'code' => 532,
                    'success' => false,
                    'data' => '',
                    'message' => 'Invalid JSON data, ' . json_last_error_msg()
                ]));
                return $response
                    ->withHeader('Content-Type', 'application/json')
                    ->withStatus(532);
            }
        }

        // 解析正常，继续处理请求
        return $handler->handle($request);
    }
}
